import db
import math
import datetime

db.init()

NOW = datetime.datetime.now()

for item in db.Item.select():
	data = []
	for auction in db.Auction.select(db.Auction.q.item == item):
		data.append((auction.quantity, auction.buy, auction.bid))
	if len(data) > 0:
		vbuy, vbid = 0, 0
		volume, totalBuy, totalBid = 0, 0, 0
		for quantity, buy, bid in data:
			volume += quantity
			if buy:
				vbuy += quantity
				totalBuy += buy
			if bid:
				vbid += quantity
				totalBid += bid
		if vbuy > 0:
			avgBuy = totalBuy / vbuy
		else:
			avgBuy = None
		if vbid > 0:
			avgBid = totalBid / vbid
		else:
			avgBid = None
		sdBuy, sdBid = 0, 0
		for quantity, buy, bid in data:
			if buy and avgBuy:
				a = avgBuy - (buy / quantity)
				sdBuy += quantity * (a * a)
			if bid and avgBid:
				b = avgBid - (bid / quantity)
				sdBid += quantity * (b * b)
		if avgBuy:
			sdBuy = int(math.sqrt(sdBuy))
		else:
			sdBuy = None
		if avgBid:
			sdBid = int(math.sqrt(sdBid))
		else:
			sdBid = None
		print item.name, volume, avgBuy, avgBid, sdBuy, sdBid
		db.ItemHistory(date = NOW, item = item,
			volume = volume, avgPpuBuy = avgBuy, avgPpuBid = avgBid,
			stdDevPpuBuy = sdBuy, stdDevPpuBid = sdBid)
